package com.kuwei.servlet.frame;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.kuwei.utils.CommonUtils;

/**
 * servlet抽象类  主要放通用方法
 * @author zyc
 *
 */
public abstract class BaseServlet{
	
	@Autowired
	protected SqlSessionDaoSupport sqlSessionDaoSupport;
	
	/**
	 * 获取service
	 * @param request
	 * @param serviceName
	 * @return
	 */
	public Object getService(HttpServletRequest request,String serviceName){
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
		return ctx.getBean(serviceName);
	}
	
	/**
	 * 输入流转字符串
	 * @param is
	 * @param characterEncoding
	 * @return
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static String convertToString(InputStream is, String characterEncoding) throws IOException,UnsupportedEncodingException {
		if (is == null)
			return null;
		
		String str = "";
		if (null == characterEncoding  || characterEncoding.equals("")) {
			characterEncoding = "utf-8"; // // 默认以utf-8形式
		}
		BufferedReader reader = null;
		reader = new BufferedReader(new InputStreamReader(is, characterEncoding));
		StringBuffer sb = new StringBuffer();
		while ((str = reader.readLine()) != null) {
			sb.append(str).append("\n");
		}
		if(null != reader)
			reader.close();

		return sb.toString();
	}
	
	public String handleNullString(Object obj){
		if(!CommonUtils.isEmpty(obj))
			return obj.toString();
		else
			return null;
	}
	
}
